/**
 * Created by Administrator on 2017/1/15.
 */

var config = require('./config');

var MJ = require('../MJ/MJ');
var MJRoom = require('../MJ/room').MJRoom;

var Const = require('./const');
var SubCode = require('../subCode');

var YouJinStatus = {
    'CHI': 2,       //2吃游,3碰游
    'PENG': 3
};

exports.QZMJRoom = MJRoom.extend({

    baoCard: 0,                 //金牌
    startPlayCard: false,               //开始出牌
    _firstRound: true,
    _curYouJin: false,               //游金
    _youJinStat: 0,             //2吃游,3碰游
    curfeng: {},
    _scoreRate: 0,
    _num1: 0,
    _num2: 0,
    init: function (rid, creator, msg) {
        this._super(rid, creator, msg);
        this.baoCard = 0;
        this.startPlayCard = false;
        this._curYouJin = false;
        this.curfeng = {};
        this._scoreRate = 0;
        this._num1 = 0;
        this._num2 = 0;
        this._firstRound = true;
        var config = this.getSceneConfig();
        if(config){
            this._scoreRate = config.scoreRate;
        }
        this._youJinStat = 0;

    },
    checkInit: function () {
        return this._super();
    },

    /******************************************************************
     * 重载的接口
     ******************************************************************/
    isFinalRound: function(){
        var subConfig = this.getSubConfig();

        if (this.isSceneRoom()) {
            return false;
        }

        if(subConfig.options.FAN50){
            var final = false;
            this.enumPlayers(function (eIndex, ePlayer) {
                if(ePlayer.mode50 <= -50){
                    final = true;
                }
            });
            return final;
        }else {
            return this._curRound >= this._round;

        }

    },

    getRoomConfig: function () {
        var cfg = this._super();
        cfg.destroyWaitTime = 120;
        cfg.waitTimeoutTime = 60;
        return cfg;
    },
    /*getMaxPlayer:function(){
        return this.getOption('RenShu');
    },*/
    getInfo: function () {
        var info = this._super();

        info.scoreRate = this._scoreRate;

        info.jinCard = this.baoCard;

        return info;
    },

    getRoundInfo: function () {
        var info = this._super();
        return info;
    },

    getReconnectInfo: function (rePlayer) {
        var info = this._super(rePlayer);
        info.jinCard = this.baoCard;
        info.num1 = this._num1;
        info.num2 = this._num2;
        info.scoreRate = this._scoreRate;
        return info;
    },

    onBeforeStartNewRound: function () {
        this._super();
        this.startPlayCard = false;
        this._curYouJin = false;
        this._num1 = 0;
        this._num2 = 0;
        this.curfeng = {};
        this._youJinStat = 0;
    },
    onBeforeNewCard: function(){
        if(this._publicCards.getRemainNum() <= 14 ) {
            this.settlementCurRound(0);
        }
        this._youJinStat = 0;
    },
    onAfterStartNewRound: function () {
        this._super();
        //定庄
        if(this._firstRound){
            this._firstRound = false;
            this._num1 = ExNumber.rand(6) + 1;
            this._num2 = ExNumber.rand(6) + 1;
            var iTemp = this._num1 + this._num2;
            for(var i = 0; i < iTemp - 1; i++){
                this._dealerIndex = this.getNextPlaying(this._dealerIndex);
            }
            var msg ={
                num1 : this._num1,
                num2 : this._num2,
                dealerIndex: this._dealerIndex,
            };
            this.broadcast("onYaoShaiZi", msg);
        }
        if(!this.getOption('KMG')){
            this.preStartPlay();
        } else {
            var now = this.getNowTime();
            this.enumPlaying(function(eIndex, ePlayer) {
                ePlayer.setWaitHandleTime(now);
            });
        }
    },
    onPlayerEnter: function (player) {
        this._super(player);
        this.setReadyTimer(player);
    },
    preStartPlay: function () {

        this.initPlayersHandCards();
        this.startPlay();
    },
    setReadyTimer: function(player){
        var subConfig = this.getSubConfig();
        var room = this;
        if(this.isSceneRoom()){
            if(!player.isReady()){
                player._readyTimer = setTimeout(function(){
                    if(!player.isReady()){
                        room.handlePlayerReady(player, {}, function(){});
                    }
                },subConfig.readyWaitTime);
            }
        }
    },
    startPlay: function () {
        var subConfig = this.getSubConfig();

        var card = {
            jincard: 0,
        };
        var cards = this._publicCards.cards;
        var i = 1;
        do{
            this.baoCard = cards[cards.length - i];
            //this.baoCard = 16;

            i++;
        }while (MJ.getColor(this.baoCard) == MJ.Color.HUA && i < 9);
        card.jincard = this.baoCard;
        this.broadcast("onJinCard", card);

        this.enumPlayers(function (eIndex, ePlayer){
            this._curPlay = eIndex;
            var hua = ePlayer.checkHua();
            if(hua.length > 0){
                this.onHuaCard(hua);
            }
        }.bind(this),this.getDealerIndex());
        //this._curPlay = this.getDealerIndex();


        this.startPlayCard = true;
        //var dealer = this.getDealerIndex();
        logger.debug("room=%d sendHangupTask in=QZMJ.startPlay", this.rid());
        this._sendHangupTask(this._startPlay);
    },

    _startPlay: function () {
        this._changeCurPlay(this.getDealerIndex());
        this._doCheckNewCardHangupTask();
    },

    onBeforePlayCard: function (player, msg, card) {
        var code = this._super(player, msg, card);
        if (code) {
            return code;
        }

        /*if(this._curTask == MJ.Task.CHI){
            if(card == player._chiCards[player._chiCards.length - 1].card){
                return SubCode.MJ_PLAY_FAILED;
            }
        }*/
        //this._curGang = (task == MJ.Task.GANG) ? (this._curGang + 1) : 0;
        if (player.isBaoTing() && card != player.getLastCard()) { //天听不能换牌
            return SubCode.MJ_IS_BAOTING;
        }
        if(MJ.getColor(card) == MJ.Color.HUA){
            return SubCode.MJ_PLAY_FAILED;
        }
        if(player._ftgd.length){
            for (var i = 0; i < player._ftgd.length; i++){
                if(card == player._ftgd[i]){
                    return 0;
                }
            }
            return SubCode.MJ_PLAY_FAILED;
        }
    },
    onAfterPlayCard: function (player, card, playInfo) {
        this._super(player, card, playInfo);
        var room = this;
        if(playInfo.card < 8 && this.getOption('FTGD')){
            if(!this.curfeng[playInfo.card]){
                this.curfeng[playInfo.card] = this.getPlayerCount();
            }
        }
        /*ExObject.eachKeyNum(this.curfeng, function(c, n){
            if(n){
                room.curfeng[c] -= 1;
            }
        });*/
        /*
        player._hundiao = false;
        if( player._hundiao == false){
            if(player.checkHunDiao(player._handCards.getCards())){
                player._hundiao = true;
            }
        }*/

    },

    checkNewCardHangupTask: function () {
        var player = this.getCurPlayer();
        var room = this;
        var hua = player.checkHua();
        if(hua.length){
            return;
        }
        if(!room.startPlayCard){
            return;
        }

        var huIndexs = [];
        var huPattern = player.checkHu();
        if (huPattern != Const.Pattern.NONE) {
            var rules = [];

            var jinCard = this.getBaoCardNum(player);
            if(!jinCard){
                jinCard = 0;
            }
            if(jinCard > 0){
                var cards = player.getHandCards();
                var newCards = clone(cards);
                newCards[room.baoCard] -= 1;
                if(player.checkYouJing(newCards)){
                    rules.push(Const.ScoreRule.YOU);
                }
            }
            if (player.isFirstHand()){
                if (player.getIndex() == this.getDealerIndex()) {
                    rules.push(Const.ScoreRule.TH);
                }
            }
            if (this.getCurGang()){
                rules.push(Const.ScoreRule.GSH);
            }

            var card = player.getLastCard() || player.getInitLastCard();

            if(player.youjin == 0 && huPattern == Const.Pattern.SANJIN){
                rules.push(Const.ScoreRule.SANYOU);
            }else {
                huPattern = MJ.Pattern.NORMAL;
            }
            this._hangupTask.addHuTask(player.getIndex(), card, player.getIndex(), huPattern, rules);
            huIndexs.push(player.getIndex());
        }
        /*if(player.youjin){
            //this._hangupTask.addTingTask(player.getIndex(),[]);
            player.send('onYouJin',{})

        }*/
        var gangArray = player.checkGang();
        if (gangArray.length > 0 && this._curYouJin == false) {
            this._hangupTask.addGangTask(player.getIndex(), gangArray);
        }

    },


    checkPlayCardHangupTask: function (card) {
        var player = this.getCurPlayer();
        player._selectCard = 0;
        this._checkPlayCardHangupTask(card);

    },
    checkCurPlayHangupTask: function() {
        var player = this.getCurPlayer();
        if (!player.isBaoTing() && this._curYouJin == false) {
            var gangArray = player.checkGang();
            if (gangArray.length > 0) {
                this._hangupTask.addGangTask(player.getIndex(), gangArray);
            }
        }
        if(this._curYouJin){
            if(this._youJinStat){
                this._doYouJin(player);
                return;
            }
        }
        this.onAfterNewCard();
    },

    _checkPlayCardHangupTask: function (card) {
        var curPlay = this.getCurPlay();
        var nextIndex = this.getNextIndex(curPlay);

        var curPlayer = this.getCurPlayer();
        if (!curPlayer.getLastCard() || curPlayer.getLastCard() != card) { // 不是打的上次摸的牌，则重新检查听牌
            //var tings = curPlayer.checkTing();
            //curPlayer.setTingCards(tings);
        }
        var room = this;
        var wpy = 0;
        this.enumPlayers(function (eIndex, ePlayer) {
            if (eIndex != curPlay && !ePlayer.isRoundHu()) {
                if (ePlayer.checkPengWithCard(card) && curPlayer._youjin == false) {
                    this._hangupTask.addPengTask(eIndex, card, curPlay);
                    wpy = YouJinStatus.PENG;
                }
                if (eIndex == nextIndex && curPlayer._youjin == false) { // 下家可以吃牌
                    var maxCards = ePlayer.checkChiWithCard(card);
                    if (maxCards) {
                        this._hangupTask.addChiTask(eIndex, card, curPlay, maxCards);
                        var wy = this.checkYouJinIfChi(ePlayer, card, maxCards);
                        if(wy){
                            ePlayer._selectCard = wy;
                            wpy = YouJinStatus.CHI;
                        }
                    }
                }
                if (!ePlayer.isPassHu()) {
                    if(this.getBaoCardNum(ePlayer) > 1 && this.getOption('SJBPH')){

                    }else {
                        var huPattern = ePlayer.checkHuWithCard(card);
                        if (huPattern != Const.Pattern.NONE) {
                            var rules = [];
                            if(wpy == YouJinStatus.CHI){
                                rules.push(Const.ScoreRule.YOU);
                                this._youJinStat = wpy;
                            }else if(wpy > 1){
                                var cards = ePlayer.getHandCards();
                                var newCards = clone(cards);
                                ExObject.addNumber(newCards, card, 1);
                                if(newCards[room.baoCard]) {
                                    newCards[room.baoCard] -= 1;
                                    if (ePlayer.checkYouJing(newCards)) {
                                        rules.push(Const.ScoreRule.YOU);
                                        this._youJinStat = wpy;
                                    }
                                }
                            }
                            if (this.getCurGang() > 0) {
                                rules.push(Const.ScoreRule.GSP);
                            }
                            this._hangupTask.addHuTask(ePlayer.getIndex(), card, curPlay, huPattern, rules);
                        }
                    }
                }

                if (ePlayer.checkGangWithCard(card) && curPlayer._youjin == false) {
                    this._hangupTask.addGangTask(eIndex, [{card: card, from: curPlay, gang: MJ.Gang.DIAN}]);
                }
            }
        }.bind(this));
    },
    checkYouJinIfChi: function(player, chiCard, maxCards){
        var resp = 0;
        var cards = player.getHandCards();
        for(var i = 0; i < maxCards.length; i++){
            var newCards = clone(cards);
            ExObject.addNumber(newCards, chiCard, 1);
            this.chiCardOfYou(newCards, maxCards[i]);
            if(newCards[this.baoCard]){
                this.delCard(newCards, this.baoCard);
                if(player.checkYouJing(newCards)){
                    resp = maxCards[i];
                    break;
                }
            }
        }
        return resp;
    },
    delCard: function(cards, card) {
        var num = cards[card];
        if (num) {
            if (num <= 1) {
                delete cards[card];
            } else {
                cards[card] = num - 1;
            }
            return true;
        }
        return false;
    },
    chiCardOfYou: function(cards, maxCard){
        var selectCard = maxCard;
        if (MJ.getPoint(selectCard) < 3) {
            return false;
        }

        var exist = true;
        for (var i = 0; i < 3; ++i) {
            var tmpCard = selectCard - i;
            if (cards[tmpCard] < 1) {
                exist = false; break;
            }
        }

        if (!exist) {
            return false;
        }

        for (var i = 0; i < 3; ++i) {
            var tmpCard = selectCard - i;
            this.delCard(cards, tmpCard);
        }
        return true;
    },
    onAfterNewCard: function(){
        var player = this.getCurPlayer();
        var hua = player.checkHua();
        if(hua.length > 0){
            this.onHuaCard(hua);
            return;
        }
        var room = this;
        if(this.getOption('FTGD')){
            player._ftgd = [];
            ExObject.eachKeyNum(this.curfeng, function(c, n){
                if(n){
                    var cards = player.getHandCards();
                    if(cards.hasOwnProperty(c)) {
                        if(cards[c] == 1){
                            player._ftgd.push(c);
                        }
                    }
                }
            });
            if(player._ftgd.length) {
                this.broadcast("onfeng",{cards : player._ftgd});
            }
        }
    },
    checkGangHangupTask: function (playerIndex, gangInfo) {
        var card = gangInfo.card;
        if (gangInfo.type) {
            card = gangInfo.buCard;
        }

        var huIndexs = [];

        this.enumPlayers(function (eIndex, ePlayer) {
            if (eIndex != playerIndex && !ePlayer.isRoundHu() && !ePlayer.isPassHu() && ePlayer.getBaoTingPassHuTimes() < 1) {
                var huPattern = ePlayer.checkHuWithCard(card);
                if (huPattern != Const.Pattern.NONE) { // 抢杠
                    var rules = [];
                    var player = ePlayer;
                    var room = this;

                    rules.push(Const.ScoreRule.QG);


                    this._hangupTask.addHuTask(eIndex, card, playerIndex, huPattern, rules);
                    huIndexs.push(eIndex);
                }
            }
        }.bind(this));
    },

    checkGangNewCard: function (gangInfo) {
        if(gangInfo.type){
            return false
        }
        return true;
    },

    checkHuSettlement: function () {
        return true;
    },

    onSettlementHuTask: function (task) {
        var playerIndex = task.playerIndex;
        var pattern = task.pattern;
        var card = task.card;
        var from = task.from;
        var rules = task.rules;
        var huPlayer = this.getPlayerByIndex(playerIndex);

        var isZM = (playerIndex == from); // 是否是自摸

        var targetsIndex = [];
        var targets = [];
        if (isZM) {
            this.enumPlayers(function (eIndex, ePlayer) {
                if (eIndex != playerIndex && !ePlayer.isRoundHu()) {
                    targetsIndex.push(eIndex);
                    targets.push(ePlayer);
                }
            });
        } else {
            huPlayer.addRoundItemScores(Const.ScoreRule.DH, Const.ItemScore[Const.ScoreRule.DH]);
            huPlayer.setRoundScoreRule(Const.ScoreRule.DH);
            targetsIndex.push(from);
            targets.push(this.getPlayerByIndex(from));
            var dpPlayer = this.getPlayerByIndex(from);
            dpPlayer.isDianPao = true;
        }
        /*if(this._youJinStat > 1){
            huPlayer._handCards.delCard(card);
        }*/

        for (var i = 0; i < rules.length; ++i) {
            var rule = rules[i];
            switch (rule) {
                case Const.ScoreRule.QG:
                    if (!isZM) {
                        var targetPlayer = targets[0];
                        if (targetPlayer.getIndex() == this.getCurPlay() && this.getCurGang() > 0) { // 抢杠的被抢玩家一定是当前玩家
                            targetPlayer.setRoundScoreRule(rule);
                            targetPlayer.cancelLastGangForQG(card);
                        }
                    }
                    break;
                case Const.ScoreRule.GSP:
                    if (!isZM) {
                        var targetPlayer = targets[0];
                        targetPlayer.setLastGangUnscored();
                    }
                    break;
                default:
                    break;
            }
            huPlayer.setRoundScoreRule(rule);
            huPlayer.addRoundItemScores(rule, Const.ItemScore[rule]);
        }
        if(isZM){
            if(pattern == Const.Pattern.NORMAL){
                pattern = Const.Pattern.ZM;
            }
            if(pattern == Const.Pattern.ZM && huPlayer._youjin){
                pattern = Const.Pattern.YOUJIN;
            }
            if(pattern == Const.Pattern.EIGHTHUA){
                pattern = Const.Pattern.ZM;
            }
            if(pattern == Const.Pattern.SANJIN ){
                if(huPlayer._youjin){
                    pattern = Const.Pattern.YOUJIN;
                }else if(huPlayer.youjin){
                    pattern = Const.Pattern.ZM;
                }
            }
        } else {
            pattern = Const.Pattern.NORMAL;

        }

        var patternScore = Const.PatternScore[pattern];
        var huResult = isZM ? MJ.Result.ZM : MJ.Result.DH;

        huPlayer.setRoundResult(huResult, targetsIndex, card);
        huPlayer.setRoundPattern(pattern, patternScore);

        this.broadcast("onPlayerHu", {
            playerIndex: playerIndex,
            card: card,
            from: from,
            pattern: pattern
        });
    },

    onSettlement: function () {
        var player = this.getPlayerByIndex(this._curPlay);

        var subConfig = this.getSubConfig();
        //logger.debug("room=%d youJinHandCard in=QZMJ.handleYouJin cards = %j", this.rid(),player.getHandCards());

        /*var huPlayer = this.getPlayerByIndex(this.getFirstHuPlayerIndex());
        if(huPlayer.getRoundResult() == MJ.Result.DH){
            var tempPlayer = this.getPlayerByIndex(this.getFirstDPIndex());
            if(tempPlayer._youjin){
                tempPlayer._handCards.delCard(tempPlayer.youjin);
            }
        }*/
        var settlement = true;
        this.enumPlayers(function (eIndex, ePlayer) {
            ePlayer.settlementGangScore();
        }.bind(this));
        this.enumPlayers(function (eIndex, ePlayer) {
            if(ePlayer.getMark("forceQuit")){
                settlement = false;
            }
        }.bind(this));

        this.enumPlayers(function (eIndex, ePlayer) {
            ePlayer.settlementRules();
        }.bind(this));
        if(settlement){
            this.enumPlayers(function (eIndex, ePlayer) {
                if(subConfig.options.FAN50){
                    ePlayer.settlementPatternScore50();
                }else {
                    ePlayer.settlementPatternScore();
                }
            }.bind(this));
        }
        this.enumPlayers(function (eIndex, ePlayer) {
            ePlayer.mode50 = ePlayer.getScore();
        }.bind(this));
    },
    //补花
    onHuaCard: function(huaCards){
        var player = this.getCurPlayer();
        player.playHua(huaCards);
        var cards = [];
        for(var i = 0; i < huaCards.length; i++){
            var card = this._publicCards.getCard();
            cards.push(card);
            player.addNewCard(card);
        }
        this.broadcast("onPlayHua", {
            playerIndex: player.getIndex(),
            cards: huaCards,
            newCards: cards
        });
        this._curGang++;
        var hua = player.checkHua();
        if(hua.length > 0){
            this.onHuaCard(hua);
        }else{
            this._doCheckNewCardHangupTask();
            this.onAfterNewCard()
        }
    },
    onPlayerQuitRoom: function(player){
        this._super(player);
        if(this.isSceneRoom()){
            if(player._readyTimer){
                clearTimeout(player._readyTimer);
            }
        }
    },
    onCurRoundFinished: function () {
        this._super();
        // 计算新的庄家
        if(this._dealerIndex == this.getFirstHuPlayerIndex()){
            this._dealerLZ++;
        }else {
            this._dealerIndex = this.getNextIndex(this._dealerIndex);
            this._dealerLZ = 1;
        }
        /*
        if(this.isRoundHZ()){
            this._dealerIndex = this.getNextIndex(this._dealerIndex);
            this._dealerLZ = 1;

        }else {
            if(this._huTasks.length > 1){
                this._dealerIndex = this.getFirstDPIndex();
            }else {
                if (this.getFirstHuPlayerIndex() == this._dealerIndex) {
                    this._dealerLZ++;
                } else {
                    //this._dealerIndex = this.getNextIndex(this._dealerIndex);
                    this._dealerIndex = this.getFirstHuPlayerIndex();
                    this._dealerLZ = 1;
                }
            }
        }*/
        this.enumPlayers(function (eIndex, ePlayer) {
            ePlayer._selectMAI = -1;
        }.bind(this));
        if(this.isSceneRoom()){
            this.enumPlayers(function (eIndex, ePlayer) {
                clearTimeout(ePlayer._readyTimer);
                this.setReadyTimer(ePlayer);
            }.bind(this));
        }
        this.broadcast("onDealerChanged", {
            dealer: this._dealerIndex,
            dealerLZ: this._dealerLZ
        });
    },
    _doYouJin: function(player){
        player._youjin = true;
        //打出游金的单牌
        var sendCard = {
            card: player.youjin,
            playerIndex: player.getIndex(),
        };
        this.broadcast("onYouJingHuCard", sendCard);

        this._hangupTask.reset();
        player._handCards.delCard(player.youjin);
        this.checkPlayCardHangupTask(player.youjin);
        logger.debug("room=%d sendHangupTask in=QZMJ.handleYouJin", this.rid());
        this._sendHangupTask(this.onYouJin);

    },
    onYouJin: function(){
        var room = this;
        var player = this.getPlayerByIndex(this._curPlay);
        if(room.getHuPlayerCount() > 0){
            return;
        }
        room.broadcast("onYouJinHuCardPass", {
            playerIndex: this._curPlay,
        });
        //打出游金的单牌
        /*var sendCard = {
            card: player.youjin,
        };
        room.broadcast("onYouJingHuCard", sendCard);
        this.enumPlaying( function (eIndex, ePlayer) {
            if (eIndex == player.getIndex()) {
                return;
            }
            if(room.getHuPlayerCount() > 0){
                return;
            }
            var huPattern = ePlayer.checkHuWithCard(player.youjin);
            if (huPattern != Const.Pattern.NONE) {
                var rules = [];
                room._hangupTask.reset();
                var card = ePlayer.getLastCard() || ePlayer.getInitLastCard();
                room._hangupTask.addHuTask(eIndex, card, eIndex, huPattern, rules);
                //room._hangupTask.submitTask(eIndex, MJ.Task.HU);
                logger.debug("room=%d onPlayerHu player = %j,", room.rid(), eIndex);
            }
        }, player.getIndex());
        if(room.getHuPlayerCount() > 0){
            return;
        }*/
        //给每个玩家发一张牌
        this.enumPlaying( function (eIndex, ePlayer) {
            if(eIndex == player.getIndex()){
                return;
            }
            var msg = {
                getCard: 0,
                playerIndex: 0,
            };
            var card = room._publicCards.getCard();
            ePlayer.addNewCard(card);
            msg.getCard = card;
            msg.playerIndex = eIndex;
            room.broadcast("onYouJinCard", msg);
        }, player.getIndex());

        //检测每个玩家是否能胡
        var curIndex = room.getNextPlaying(room._curPlay);
        var curPlayer = room.getPlayerByIndex(curIndex);
        this.enumPlaying( function (eIndex, ePlayer) {
            if(room.getHuPlayerCount() > 0){
                return;
            }
            if(eIndex == this._curPlay){
                player._handCards.addCard(player.youjin);
            }
            //logger.debug("room=%d onYouJin player = %j,", room.rid(), eIndex);
            logger.debug("room=%d onYouJin player = %d ,curIndex = %d, _curPlay = %d", room.rid(), eIndex, curIndex, this._curPlay);

            var huPattern = ePlayer.checkHu();
            if (huPattern != Const.Pattern.NONE) {
                //dealHangupTaskHu
                var rules = [];
                room._hangupTask.reset();
                var card = ePlayer.getLastCard() || ePlayer.getInitLastCard();
                if(eIndex == this._curPlay){
                    card = player.youjin;
                }
                room._hangupTask.addHuTask(eIndex, card, eIndex, huPattern, rules);
                logger.debug("room=%d onYouJin player = %d ,curIndex = %d, _curPlay = %d", room.rid(), eIndex, curIndex, this._curPlay);
                if(room._curPlay == eIndex){
                    //room.broadcast("onYouJinHu", {});
                    room._hangupTask.submitTask(eIndex, MJ.Task.HU);

                }else {
                    var curPlayIndex = [];
                    curPlayIndex.push(room.getNextPlaying(eIndex));
                    room._sendHangupTask(room.nextYouJin,curPlayIndex);
                    return false;
                }
                //room._hangupTask.submitTask(eIndex, MJ.Task.HU);
            }
        }.bind(this), curIndex);
    },
    nextYouJin: function(curIndex){
        var room = this;
        var player = this.getPlayerByIndex(this._curPlay);

        this.enumPlaying( function (eIndex, ePlayer) {
            if(room.getHuPlayerCount() > 0){
                return;
            }
            if(eIndex == this._curPlay){
                player._handCards.addCard(player.youjin);
                logger.debug("room=%d youJinHandCard in=QZMJ.handleYouJin cards = %j", room.rid(),player.getHandCards());

            }
            logger.debug("room=%d onNextYouJin player = %d ,curIndex = %d, _curPlay = %d", room.rid(), eIndex, curIndex, this._curPlay);
            var huPattern = ePlayer.checkHu();
            if (huPattern != Const.Pattern.NONE) {
                //dealHangupTaskHu
                var rules = [];
                room._hangupTask.reset();
                var card = ePlayer.getLastCard() || ePlayer.getInitLastCard();
                if(eIndex == this._curPlay){
                    card = player.youjin;
                }
                room._hangupTask.addHuTask(eIndex, card, eIndex, huPattern, rules);
                if(room._curPlay == eIndex){
                    //room.broadcast("onYouJinHu", {});
                    room._hangupTask.submitTask(eIndex, MJ.Task.HU);

                }else {
                    var curPlayIndex = [];
                    curPlayIndex.push(room.getNextPlaying(curIndex));
                    room._sendHangupTask(room.nextYouJin,curPlayIndex);
                    return false;
                }
                //room._hangupTask.submitTask(eIndex, MJ.Task.HU);
            }
        }.bind(this), curIndex);
    },
    /******************************************************************
     * 消息处理
     ******************************************************************/

    //
    handleSelectMAI: function (player, msg, callback) {
        if (!this.isPlaying()) {
            callback({code: Code.ROOM_NOT_PLAYING});
            return;
        }
        var subConfig = this.getSubConfig();

        if (player.isMAISelected()) {
            callback({code: SubCode.MAI_STATUS_ERROR});
            return;
        }

        player._selectMAI = msg.mai;

        var MSG = {
            playerIndex: 0,
            mai: 0,
        };
        MSG.playerIndex = player._index;
        MSG.mai = msg.mai;
        this.broadcast("onSelectMAI", MSG);
        callback({});
        player.setWaitHandleTime(0);
        var isAllSelected = true;
        var DealerIndex = this.getDealerIndex();
        this.enumPlayers(function(eIndex, ePlayer) {
            if (!ePlayer.isMAISelected()) {
                isAllSelected = false;
            }
        });
        if (isAllSelected) {
            this.preStartPlay();
        }
    },
    //游金
    handleYouJin: function (player, msg, callback) {
        player.setWaitHandleTime(0);

        if (!this.isPlaying()) {
            callback({code: Code.ROOM_NOT_PLAYING});
            return;
        }
        if (player.getIndex() != this.getCurPlay() && this._youJinStat < YouJinStatus.CHI) {
            callback({code: SubCode.NOT_CUR_PLAY}); return;
        }
        var tempTask = this._hangupTask.getPlayerTask(player.getIndex(),MJ.Task.HU);
        if(tempTask.pattern == Const.Pattern.SANJIN){
            this._hangupTask.submitTask(player.getIndex(), MJ.Task.HU);
            callback({});
            return;
        }
        if(!player.youjin){
            callback({code : SubCode.NOT_YOU_JIN});
            return;
        }
        this._curYouJin = true;
        if(this._youJinStat == YouJinStatus.CHI){
            if (!this._hangupTask.existTask(player.getIndex(), MJ.Task.CHI)) {
                callback({code: SubCode.TASK_UNMATCHED}); return;
            }
            var task = this._hangupTask.getPlayerTask(player.getIndex(), MJ.Task.CHI);
            //var selectCard = this.checkYouJinIfChi(player, task.card, task.maxCards);
            var selectCard = player._selectCard;
            this._hangupTask.submitTask(player.getIndex(), MJ.Task.CHI, selectCard);
        }else if(this._youJinStat == YouJinStatus.PENG){
            if (!this._hangupTask.existTask(player.getIndex(), MJ.Task.PENG)) {
                callback({code: SubCode.TASK_UNMATCHED}); return;
            }
            this._hangupTask.submitTask(player.getIndex(), MJ.Task.PENG);
        } else {
            this._doYouJin(player);
        }
        callback({});
        //this.onYouJin();
    },


    /******************************************************************
     * 功能接口
     ******************************************************************/

    /**
     * 结算玩家是否听牌
     * @param player
     * @private
     */

    //随机获取一张牌
    getRandomCard: function () {
        var index = ExNumber.rand(this._publicCards.cards.length - 1);
        var card = this._publicCards.cards[index];
        return card;
    },
    //获取玩家宝牌数量
    getBaoCardNum: function (player) {
        return player._handCards.getCardNum(this.baoCard);
    },
    //计算牌


});